package cn.hl.hm.handler;

import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.vizhuo.utils.DateUtil;

import cn.hl.hm.constants.OrderStatus;
import cn.hl.hm.constants.PayMethod;
import cn.hl.hm.dao.RoadFeeMapper;
import cn.hl.hm.entity.RoadFee;
import cn.hl.hm.entity.UnifiedOrderRespose;

/**
 * 微信APP支付handler
 * 
 * @author 大和
 *
 */
@Service
public class WxScanPayHandler extends PayHandler {

	private static final Logger logger = Logger.getLogger(WxAppPayHandler.class);

	@Autowired
	private RoadFeeMapper roadFeeMapper;
	/**
	 * 处理微信支付请求
	 */
	@Override
	public Map<String, String> handler(Map<String, String> payMap) {
		return null;
	}

	@Override
	protected void initHandler() {
		register(PayMethod.ROAD_WX_SCAN_MER, WxScanPayHandler.class);
	}

	/**
	 * 回调请求
	 */
	@Override
	public Boolean callback(HttpServletRequest request, HttpServletResponse response) {
		try {
			BufferedReader reader = request.getReader();
			String line = "";
			StringBuffer inputString = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				inputString.append(line);
			}
			if (reader != null) {
				reader.close();
			}
			logger.info("----[微信回调]接收到的报文---" + inputString.toString());
			XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));// 说明3(见文末)
			xStream.alias("xml", UnifiedOrderRespose.class);
			UnifiedOrderRespose unifiedOrderRespose = (UnifiedOrderRespose) xStream.fromXML(inputString.toString());
			
			
			SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			parameters.put("appid", unifiedOrderRespose.getAppid()); // 微信开放平台审核通过的应用APPID
			parameters.put("attach", unifiedOrderRespose.getAttach()); // 商家数据包
			parameters.put("bank_type", unifiedOrderRespose.getBank_type()); // 微信支付分配的商户号
			parameters.put("cash_fee", unifiedOrderRespose.getCash_fee()); // 现金支付金额
			parameters.put("fee_type", unifiedOrderRespose.getFee_type()); // 货币种类
			parameters.put("is_subscribe", unifiedOrderRespose.getIs_subscribe());// 是否关注公众账号
			parameters.put("mch_id", unifiedOrderRespose.getMch_id()); // 商户号
			parameters.put("nonce_str", unifiedOrderRespose.getNonce_str());
			parameters.put("openid", unifiedOrderRespose.getOpenid());// 用户标识
			parameters.put("out_trade_no", unifiedOrderRespose.getOut_trade_no()); // 商户订单号
			parameters.put("result_code", unifiedOrderRespose.getResult_code()); // 业务结果
			// parameters.put("return_code",
			// unifiedOrderRespose.getReturn_code());
			parameters.put("time_end", unifiedOrderRespose.getTime_end()); // 支付完成时间
			parameters.put("total_fee", unifiedOrderRespose.getTotal_fee()); // 总金额
			parameters.put("trade_type", unifiedOrderRespose.getTrade_type()); // 交易类型APP
			parameters.put("transaction_id", unifiedOrderRespose.getTransaction_id()); // 微信支付订单号
			
			logger.info("开始进入支付成功方法里：");
			if (null != unifiedOrderRespose && "SUCCESS".equals(unifiedOrderRespose.getReturn_code())) {
				logger.info("已经进入支付成功方法里------：unifiedOrderRespose"+unifiedOrderRespose.toString());
				if (StringUtils.isBlank(unifiedOrderRespose.getOut_trade_no())) {
					return false;
				}
				return processBusiness(unifiedOrderRespose);
			} else {
				return false;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;

		}

	}

	private Boolean processBusiness(UnifiedOrderRespose unifiedOrderRespose) {
		// 查订单
		RoadFee orderInfo = new RoadFee();
		orderInfo.setOrderCode(unifiedOrderRespose.getOut_trade_no());
		List<RoadFee> selectPageList = roadFeeMapper.selectRoadFees(orderInfo);
		//解決paramError
		if(selectPageList!=null&&selectPageList.size()>0){
			
		}else {
			return false;
		}
		if (selectPageList != null && selectPageList.size() > 0) {
			RoadFee order = selectPageList.get(0);
			logger.info("......回调排查信息：  订单 "+order.toString());
			if (StringUtils.isBlank(unifiedOrderRespose.getSign())) {// 签名为空
				return false;
			}
			
			String orderStatus = order.getOrderStatus();
			if (orderStatus.equals("1")) {
				String userPaymentTime = unifiedOrderRespose.getTime_end();// 支付时间
				logger.info("......支付时间" + userPaymentTime);
				if (userPaymentTime != null && !("null".equals(userPaymentTime))) {
				

				} else {
					userPaymentTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				}
				Date string2Date = DateUtil.string2Date(userPaymentTime, "yyyyMMddHHmmss");
				logger.info("......转换后支付时间" + string2Date);
				// 1 修改订单
				RoadFee orderUpParam = new RoadFee();
				orderUpParam.setId(order.getId());
				orderUpParam.setOrderStatus("2");
				orderUpParam.setPayTime(string2Date);
				orderUpParam.setPaymentNo(unifiedOrderRespose.getOpenid());
				orderUpParam.setPayTransNo(unifiedOrderRespose.getTransaction_id());
				orderUpParam.setPayType(PayMethod.ROAD_WX_SCAN_MER.getCode());
				int updateOrderById = roadFeeMapper.updateByPrimaryKey(orderUpParam);
				if (updateOrderById > 0) {
					return true;
				}else {
					return false;
				} 
			} else {
				logger.info("......订单"+order.getOrderCode()+"...状态 "+orderStatus+"...不处理 返回true");
				return true;
			}

		} else {
			return false;
		}
	}

}
